package com.zzyang.mybatis.jdbc.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.*;

/**
 * 数据源上下文
 *
 * @author zhuoziyang
 * @date 2021/4/8 21:11
 */
public class DefaultRoutingDataSource extends AbstractRoutingDataSource {

    @Autowired
    private DataSourceContext dataSourceContext;

    @Autowired
    private RoutingDataSourceKeyDecider keyDecider;

    @Override
    protected Object determineCurrentLookupKey() {
        return keyDecider.decideRoutingKey();
    }

    @Override
    public void afterPropertiesSet() {
        Map<String, DataSource> allDataSource = dataSourceContext.getAllDataSource();
        Map<Object, Object> targetMap = new HashMap<>(allDataSource.size());
        allDataSource.forEach(targetMap::put);
        super.setTargetDataSources(targetMap);
        super.setDefaultTargetDataSource(dataSourceContext.getMasterDataSource());
        super.afterPropertiesSet();
    }

}
